package com.navy.list;

import java.util.*;

public class ArrayList implements ListInterface {

    private static final int DEFAULT_CAPACITY = 10;

    private int[] array;
    private int size = 0;
    private int capacity;

    public ArrayList() {
    }

    public class ArrayListIterator implements Iterator<Integer> {
        int index = 0;

        @Override
        public boolean hasNext() {
            return index < size;
        }

        @Override
        public Integer next() {
            return array[index++];
        }

        @Override
        public void remove() {
        }
    }

    public Iterator<Integer> iterator() {
        return new ArrayListIterator();
    }

    public boolean addFirst(Integer integer) {
        add(0, integer);
        return true;
    }

    public void add(int index, Integer element) {
        if (!(0 <= index && index <= size)) {
            throw new IllegalArgumentException("add index is  " + index + ", must is in [0,  " + (size) + "]");
        }

        // 1.坚持是否需要扩容 2，移动元素， 3.设置value
        checkAndInitArray();
        if (size + 1 >= capacity) { // 数组扩容
            capacity += capacity << 1;
            int[] newArray = new int[capacity];
            System.arraycopy(array, 0, newArray, 0, size);
            array = newArray;
        }
        if (index < size) {
            System.arraycopy(array, index, array, index + 1, size - index);
        }
        array[index] = element;
        size++;
    }

    public boolean addLast(Integer integer) {
        add(size, integer);
        return false;
    }

    public Integer get(int index) {
        if (array == null) {
            throw new IllegalArgumentException("array is empty when get");
        }
        checkRange(index);
        return array[index];
    }

    public Integer remove(int index) {
        if (size < 0 || index >= size) {
            throw new IllegalArgumentException("array is empty when remove ");
        }
        int value = get(index);
        if (index < size - 1) {
            System.arraycopy(array, index + 1, array, index, size - index - 1);
        }
        size--;
        return value;
    }

    public Integer removeFirst() {
        return remove(0);
    }

    public Integer removeLast() {
        return remove(size - 1);
    }

    public int[] toArray() {
        return Arrays.copyOf(array, size);
    }

    private void checkAndInitArray() {
        if (array == null) {
            array = new int[DEFAULT_CAPACITY];
            size = 0;
            capacity = DEFAULT_CAPACITY;
        }
    }

    private boolean checkRange(int index) {
        if (0 <= index && index < size) {
            return true;
        }
        throw new IllegalArgumentException("index is  " + index + ", must is in [0,  " + (size - 1) + "]");
    }
}
